import {createAsyncThunk} from "@reduxjs/toolkit";

import {PartProvider} from "type/PartProvider";
import {Part} from "type/Part";
import {Page, PagingData} from "type/Page";
import {PartGroup} from "type/PartGroup";
import {requestDelete, requestGet, requestPost, requestPut} from "util/request";
import {PartState} from "../partReducer";
/**
 * 添加Part数据
 */
export const fetchAddPart = createAsyncThunk(
    'part/fetchAddPart',
    async (part: Part) => await requestPut<Part>("/calista/part",part)
) ;

/**
 * 根据ID删除零件信息数据,删除成功返回删除的ID,失败返回undefined
 */
export const fetchDeletePart = createAsyncThunk(
    'part/fetchDeletePart',
    async (id: number) => {
        const res = await requestDelete<number>("/calista/part/" + id) ;
        return res.success ? id : void 0 ;
    }
) ;

/**
 * 根据ID更新零件信息数据,更新成功返回更新的数据,失败返回null
 */
export const fetchUpdatePart = createAsyncThunk(
    'part/fetchUpdatePart',
    async (part: Part): Promise<Part | null> => {
        let result = await requestPost<number>("/calista/part",part) ;
        return result.success ? part : null ;
    }
) ;


type Result = Page<Part> | null ;
type Param = PagingData ;
type TAPI = {
    state: { part: PartState }
}


/**
 * 查询零件信息分页数据,查找不到返回null
 */
export const fetchPageData = createAsyncThunk<Result, Param, TAPI>(
    'part/fetchPageData',
    async (paging,thunkAPI) => {
        if (!thunkAPI.getState().part.groupReady){
            await thunkAPI.dispatch(fetchPartGroup()) ;
        }
        if (!thunkAPI.getState().part.providerReady){
            await thunkAPI.dispatch(fetchPartProvider()) ;
        }
        const response = await requestGet<Page<Part>>(`/calista/part/page/${paging.current}/${paging.pageSize}`) ;
        return response.success ? response.data : null ;
    }
) ;
/**
 * 模糊查询零件信息数据,查找不到返回null
 */
export const fetchFuzzyPart = createAsyncThunk(
    'part/fetchFuzzyPart',
    async (keyword: string) => {
        const response = await requestGet<Part[]>(`/calista/part/fuzzy/${keyword}`) ;
        return response.success ? response.data : null ;
    }
);

/**
 * 获取零件分组数据
 */
export const fetchPartGroup = createAsyncThunk(
    "part/fetchPartGroup",
    async () => await requestGet<PartGroup[]>("/calista/part-group/list")
);

/**
 * 获取零件供应商数据
 */
export const fetchPartProvider = createAsyncThunk(
    "part/fetchPartProvider",
    async () => await requestGet<PartProvider[]>("/calista/part-provider/list")
) ;
